<?php

namespace App\Admin\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Collection;

/**
* Class AdminRole
 * @package App\Admin\Models
 * @property Collection $permissions
 */
class AdminRole extends Model
{
    protected $table = 'admin_roles';

    protected $fillable = ['name', 'description'];

    // 获取角色的所有权限
    public function permissions()
    {
        return $this->belongsToMany(AdminPermission::class, 'admin_role_permissions', 'role_id', 'permission_id')->withPivot(['role_id', 'permission_id']);
    }

    // 给角色分配权限
    public function assignPermission(AdminPermission $permission)
    {
        return $this->permissions()->save($permission);
    }

    // 删除角色权限
    public function deletePermission($permission)
    {
        return $this->permissions()->detach($permission);
    }

    // 判断角色是否拥有权限
    public function hasPermission($permission)
    {
        return $this->permissions->contains($permission);
    }
}
